<script lang="ts" setup>
import dacxService from '@/api/dacx'
import zzjgService from '@/api/zzjg'
import { SsdawsQueryResult, SsdaListQueryParam, SpdaListQueryParam } from '@/api/dacx-dto'
import { ref, onMounted, computed } from 'vue'
import { useSidebarStore } from '@/store/sidebar'
import { ElMessage } from 'element-plus'
import formBox from '@/components/queryTable/form/index.vue'
import tableBox from '@/components/queryTable/table/index.vue'
import { formItems } from '../form-item'
import { TableItem } from '@/api/common'
import dayjs from 'dayjs'
import TreeUtilDTO from '@/utils/tree'
import { useMainStore } from '@/store/main'
const mainStore = useMainStore()
// 入参
const emit = defineEmits(['addTab'])
// loading
const loading = ref<boolean>(false)
const formLabel = ref()
/**
 * 数据源
 */
const optionsObjs = ref<any>({})
// 生命周期
onMounted(async () => {
  loading.value = true
  zzjgService.getDwbm({ dwbm: mainStore.userInfo.dwbm }).then((res: any) => {
    optionsObjs.value.ljdw = res.data.data
  })
  flTreeRef.value.setCurrentKey(1)
  formLabel.value = await formItems('ssflcx')
  loading.value = false
  // 分页
  changePageNum(1)
})

const total = ref<number>(0)
const page = computed(() => {
  return {
    pageNum: form.value.pageNum,
    pageSize: form.value.pageSize,
    total: total.value,
  }
})
// 查询条件
// 诉讼档案查询条件
const ssFilter = ref({
  ajmc: '',
  ay: [],
  bgqx: '',
  bmsah: '',
  dh: '',
  dsr: '',
  gdnd: '',
  gjz: '',
  jcg: '',
  ljdw: [],
  mj: '',
})
// 视频档案查询条件
const spFilter = ref({
  bgqx: '',
  dh: '',
  gdnd: '',
  gjz: '',
  ljdw: [],
  lzz: '',
  mj: '',
  splx: '',
  tm: '',
})
const form = ref({
  pageSize: 20,
  pageNum: 1,
  filter: ssFilter.value as SpdaListQueryParam | SsdaListQueryParam,
})
/*
 * 分页
 */
const changePageNum = (val: number) => {
  form.value.pageNum = val
  getTableData()
}

/*
 * 分页
 */
const changePageSize = (val: number) => {
  form.value.pageNum = 1
  form.value.pageSize = val
  getTableData()
}

const fldm = ref(1)
const getTableData = () => {
  const params = form.value
  loading.value = true
  tableData.value.data = []
  let queryFn = null
  switch (fldm.value) {
    case 1:
      queryFn = dacxService.querySsdaList
      break
    case 31:
      queryFn = dacxService.querySpdaList
      break
  }
  queryFn &&
    queryFn(params)
      .then((res) => {
        if (res) {
          tableData.value.data = res.data.list
          total.value = res.data.total
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
      .finally(() => {
        loading.value = false
      })
}
/*
 * 查询按钮
 */
const searchTable = (data: any) => {
  const newObj: any = {}
  for (const key in data) {
    if (key.endsWith('-rq')) {
      const kssj = key.replace('-rq', 'ksrq')
      const jssj = key.replace('-rq', 'jsrq')
      if (data[key]?.length) {
        newObj[kssj] = data[key][0]
        newObj[jssj] = data[key][1]
      } else {
        newObj[kssj] = ''
        newObj[jssj] = ''
      }
    }
    newObj[key] = data[key]
  }
  form.value.filter = newObj
  getTableData()
}

/*
 * 获取表格数据
 */
const tableBoxRef = ref<InstanceType<typeof tableBox>>()
// 诉讼档案表头
const sstitles = ref([
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    custom: true,
    sort: true,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'ljdw', width: 120, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 100, dqfs: 'left' },
  { label: '案件名称', prop: 'ajmc', width: 120, dqfs: 'left' },
  { label: '部门受案号', prop: 'bmsah', width: 200, dqfs: 'left' },
  { label: '检察官', prop: 'jcg', width: 120, dqfs: 'left' },
  { label: '当事人', prop: 'dsr', width: 120, dqfs: 'left' },
  { label: '案由', prop: 'ay', width: null, dqfs: 'left' },
])
// 视频档案表头
const sptitles = ref([
  {
    label: '档号',
    prop: 'dh',
    width: 200,
    custom: true,
    sort: true,
    dqfs: 'left',
  },
  { label: '立卷单位', prop: 'ljdw', width: 120, dqfs: 'left' },
  { label: '归档年度', prop: 'gdnd', width: 120, dqfs: 'left' },
  { label: '保管期限', prop: 'bgqx', width: 120, dqfs: 'left' },
  { label: '密级', prop: 'mj', width: 100, dqfs: 'left' },
  { label: '题名', prop: 'tm', width: 120, dqfs: 'left' },
  { label: '录制者', prop: 'lzz', width: 200, dqfs: 'left' },
  {
    label: '录制日期',
    prop: 'lzrq',
    width: 160,
    dqfs: 'left',
    format: 'YYYY-MM-DD HH:mm:ss',
  },
  { label: '案由', prop: 'ay', width: null, dqfs: 'left' },
])
// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: sstitles.value,
})

// 菜单store，获取它收起/展开状态
const sideStore = useSidebarStore()

const leftSmall = ref<boolean>(false)
const rightSmall = ref<boolean>(true)

const dragFlag = ref<boolean>(false)
const moveLenLeft = ref<number>(0)
const moveLenHeight = ref<number>(0)
/*
 * 拖拽事件
 */
// 初始距离
// 是否按下
const dragstart = () => {
  dragFlag.value = true
}
const dragLeft = (e: any) => {
  if (!dragFlag.value || !e.clientX) {
    return
  }
  let left = 0
  if (sideStore.collapse) {
    left = 86
  } else {
    left = 206
  }
  if (e.clientX && e.clientX - left <= 200) {
    moveLenLeft.value = 200
  } else if (e.clientX && e.clientX - left >= 300) {
    moveLenLeft.value = 300
  } else {
    moveLenLeft.value = e.clientX - left
  }
}

const dragRight = (e: any) => {
  if (!dragFlag.value || !e.clientY) {
    return
  }
  if (e.clientY && window.innerHeight - e.clientY - 26 <= 200) {
    moveLenHeight.value = 200
  } else if (e.clientY && window.innerHeight - e.clientY - 26 >= 300) {
    moveLenHeight.value = 300
  } else {
    moveLenHeight.value = window.innerHeight - e.clientY - 26
  }
}
const dragend = () => {
  dragFlag.value = false
}

// 点击档号查看档案详情
const checkRow = (row: any) => {
  emit('addTab', { ...row, fldm: fldm.value })
}

// 点击表格数据获取档案条目
const dawsTree = ref<SsdawsQueryResult[]>()
const rowClick = (row: any) => {
  if (fldm.value === 31) {
    dawsTree.value = undefined
    rightSmall.value = true
    return
  }
  const params = {
    ajmc: row.ajmc,
    dabh: row.dabh,
  }
  dacxService
    .getSsdaws(params)
    .then((res) => {
      dawsTree.value = TreeUtilDTO.getTreeData(res.data || [], 'dm', 'fdm')
      rightSmall.value = false
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

// 左侧分类树
const flTree = ref([
  { mc: '诉讼档案', dm: 1, cj: '1', children: [] },
  { mc: '文书档案', dm: 2, cj: '1', children: [] },
  {
    mc: '音像档案',
    dm: 3,
    cj: '1',
    children: [
      {
        mc: '视频档案',
        dm: 31,
        cj: '2',
      },
      {
        mc: '音频档案',
        dm: 32,
        cj: '2',
      },
      {
        mc: '照片档案',
        dm: 33,
        cj: '2',
      },
    ],
  },
  { mc: '会计档案', dm: 4, children: [], cj: '1' },
  { mc: '其他', dm: 5, children: [], cj: '1' },
])

// 左侧分类树实例
const flTreeRef = ref()
const handleNodeClick = async (node: { mc: string; dm: number }) => {
  fldm.value = node.dm
  if (fldm.value === 1) {
    formLabel.value = await formItems('ssflcx')
    tableData.value.titles = sstitles.value
    form.value.filter = ssFilter.value
  }
  if (fldm.value === 31) {
    formLabel.value = await formItems('spflcx')
    tableData.value.titles = sptitles.value
    form.value.filter = spFilter.value
  }
  getTableData()
}

defineExpose({ changePageNum })
</script>
<template>
  <div class="container">
    <div
      class="left"
      :class="{ small: leftSmall }"
      :style="{ width: moveLenLeft ? moveLenLeft + 'px' : '' }"
    >
      <div class="left-img" @click="leftSmall = !leftSmall">
        <img src="@/assets/images/zsq.png" alt="" v-if="!leftSmall" />
        <img src="@/assets/images/ysq.png" alt="" v-else-if="leftSmall" />
      </div>
      <el-tree
        ref="flTreeRef"
        :data="flTree"
        :props="{ label: 'mc', children: 'children' }"
        node-key="dm"
        highlight-current
        @node-click="handleNodeClick"
      >
        <template #default="{ data }">
          <span class="custom-tree-node">
            <img v-if="data.cj === '1'" src="/src/assets/images/file-icon.png" alt="" />
            <img v-if="data.cj === '2'" src="/src/assets/images/text-icon.png" alt="" />
            <span>&nbsp;{{ data.mc }}</span>
          </span>
        </template>
      </el-tree>
    </div>
    <!--拖动div-->
    <div
      class="search-drag-box"
      :draggable="true"
      title="可左右拖动"
      @dragstart="dragstart()"
      @dragend="dragend()"
      @drag="dragLeft($event)"
    >
      <div class="dragImg">
        <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
      </div>
    </div>
    <div class="right" :style="{ width: moveLenLeft ? `calc(100% - ${moveLenLeft + 12}px)` : '' }">
      <div
        class="right-top"
        :style="{ height: moveLenHeight ? `calc(100% - ${moveLenHeight + 12}px)` : '' }"
      >
        <!--表单-->
        <div class="form-box">
          <form-box
            ref="formBoxRef"
            :formLabel="formLabel"
            :formData="form.filter"
            :moreShow="true"
            :optionsObj="optionsObjs"
            @searchEvent="searchTable"
          />
        </div>
        <!--表格-->
        <div class="table-box">
          <table-box
            :gnbm="fldm === 1 ? 'dacx-ssflcx' : 'dacx-spflcx'"
            ref="tableBoxRef"
            :selectShow="false"
            :table-data="tableData"
            :formParams="form"
            :getTableDataParam="page"
            :tableInfo="{ total: page.total }"
            :highlight-current-row="true"
            @changeCurrent="changePageNum"
            @changeSize="changePageSize"
            @checkRow="checkRow"
            @rowClick="rowClick"
          >
          </table-box>
        </div>
      </div>
      <!--拖动div-->
      <div
        class="table-drag-box"
        v-if="dawsTree && fldm === 1"
        :draggable="true"
        title="可上下拖动"
        @dragstart="dragstart()"
        @dragend="dragend()"
        @drag="dragRight($event)"
      >
        <div class="dragImg">
          <el-icon class="dargIcon" color="#bdcae2"><MoreFilled /></el-icon>
        </div>
      </div>
      <div
        v-if="dawsTree && fldm === 1"
        class="right-bottom"
        :class="{ small: rightSmall }"
        :style="{ height: moveLenHeight ? `${moveLenHeight}px` : '' }"
      >
        <div class="right-img" @click="rightSmall = !rightSmall">
          <img src="@/assets/images/zsq.png" alt="" v-if="!rightSmall" />
          <img src="@/assets/images/ysq.png" alt="" v-else-if="rightSmall" />
        </div>
        <el-tree
          v-show="!rightSmall"
          :data="dawsTree"
          highlight-current
          :props="{ label: 'mc', children: 'children' }"
          node-key="dm"
        >
          <template #default="{ data }">
            <span class="custom-tree-node">
              <span>{{ data.mc }} ({{ data.sl }})</span>
            </span>
          </template>
        </el-tree>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .left {
    width: 250px;
    height: 100%;
    border: 1px solid #dae4f1;
    position: relative;
    background-color: #fff;
    &.small {
      width: 16px !important;
      border: none !important;
      .el-tree {
        display: none;
      }
    }
    .el-tree {
      :deep(.el-tree-node__content) {
        height: 40px;
      }
    }
  }
  .left > .left-img {
    cursor: pointer;
    position: absolute;
    right: 0;
    top: calc(50% - 27px);
    z-index: 9;
  }
  .right {
    flex: 1;
    width: calc(100% - 262px);
    height: 100%;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    .right-top {
      flex: 1;
      height: calc(100% - 212px);
      border: 1px solid #dae4f1;
      width: 100%;
      .form-box {
        width: 100%;
        // text-align: right;
        padding: 10px;
      }
      .table-box {
        padding: 0 10px;
        height: calc(100% - 90px);
      }
      .container {
        flex-direction: column;
      }
    }
    .right-bottom {
      height: 200px;
      border: 1px solid #dae4f1;
      position: relative;
      overflow-y: auto;
      &.small {
        height: 16px !important;
        border: none !important;
      }
      .right-img {
        z-index: 9;
        cursor: pointer;
        position: absolute;
        left: calc(50% - 4px);
        top: -24px;
        transform: rotate(-90deg);
      }
    }
  }
}

.search-drag-box {
  margin: 0 1px;
  flex-shrink: 0;
  width: 10px;
  height: 100%;
  cursor: col-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;

  .dragImg {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
      transform: rotate(90deg);
    }
  }
}
.table-drag-box {
  margin: 1px 0;
  flex-shrink: 0;
  height: 10px;
  width: 100%;
  cursor: row-resize;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: row;

  .dragImg {
    height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .dargIcon {
      font-size: 29px;
    }
  }
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  border-right: none !important;
  color: #0090ff;
  background-color: #d9edff;
}
</style>
